package controllers;

import helpers.CookieHelper;
import helpers.EmailHelper;
import helpers.IdUniqueHelper;
import helpers.NumberHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import search.ArticleSearchEngine;
import search.ArticleSearchModel;
import sun.security.krb5.Config;
import systems.ConfigSystem;
import systems.LastestArticle;
import systems.Recently;
import systems.RecentlyTag;

import debugs.ArticleDebug;

import models.ArticleModel;
import models.CategoryModel;
import models.UserModel;

import entities.Article;
import entities.ArticleSearch;
import entities.Category;
import entities.SiteConfig;
import entities.User;
import forms.ArticleForm;
import forms.CaptchaForm;

public class SubmitArticleServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		SiteConfig siteConfig = ConfigSystem.getConfigs();
		
		//Get User
		User user = (User) request.getAttribute("user_logged_in");
		
		if (user == null) {
			String cookieSubmit = CookieHelper.getCookie(request, "isLoggin");
			
			if (cookieSubmit == null || cookieSubmit.isEmpty()) {
				response.sendRedirect("/confirm-login");
				return;
			}
		}
		
		String url = (String) request.getParameter("url");
		
		TreeMap check = new TreeMap();
		
		String language = siteConfig.getLanguage();
		if (language == null || language.isEmpty()) {
			language = "en";
		}
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		List<Category> categories = categoryModel.getAll();
		
		Article article = new Article();
		article.setLanguage(language);
		
		
		request.setAttribute("check", check);
		request.setAttribute("article", article);
		request.setAttribute("categories", categories);
		request.setAttribute("url", url);
		try {
			request.getRequestDispatcher("/pages/submit_article.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		SiteConfig siteConfig = ConfigSystem.getConfigs();
		
		String url = (String) request.getParameter("url");
		
		String language = siteConfig.getLanguage();
		if (language == null || language.isEmpty()) {
			language = "en";
		}
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		List<Category> categories = categoryModel.getAll();
		
		ArticleModel articleModel = ArticleModel.getInstance();
		Article article = new Article();
		article.setLanguage(language);
		
		User user = (User) request.getAttribute("user_logged_in");
		if (user != null) {
			article.setCreator(user.getId());
		} 
		
		TreeMap form = ArticleForm.checkValid(request, article);
		TreeMap check = (TreeMap) form.get("checkValid");
		article = (Article) form.get("article");
		
		if (user == null) {
			check = CaptchaForm.checkValid(request, check);
		}
		
		if (check.size() == 0) {
			//Check submitStatus config
			if (siteConfig.getSubmitStatus() == 1) {
				article.setStatus(1);
			} else {
				article.setStatus(2);
			}
			
			article.setId(IdUniqueHelper.getId());
			article.setRate(NumberHelper.getRandomNumberFrom(2, 5));
			article.setAuthKey(IdUniqueHelper.getId());
			articleModel.insert(article);
			request.setAttribute("success", "Submit article success with id " + article.getId());			
			
			//Update tag
			RecentlyTag.insert(article.getKeywords());
			
			//Update recently Cache
			if (article.getStatus() == 1) {
				Recently.update(article);
			}
			
			//Send email to author
			/*String serverUrl = UrlHelper.getServerUrl(request);
			String serverName = UrlHelper.getDomainServer(request);
			String strUrl = serverUrl + "/print-email-article?id="+article.getId()+"&key=" + article.getAuthKey();
			
			String strSubject = "[" + serverName + "] You have been submit article success on " + serverName;
			String emails = user != null ? user.getUsername() : article.getEmail() ;
			SiteConfig config = ConfigSystem.getConfigs();
			EmailHelper.sendMailFromUrl(serverName + " <" + config.getContactEmail() + ">", strSubject, strUrl, emails);*/
			
			//Send mail to admin
			/*if (siteConfig.getSubmitStatus() != 1) {
				strUrl = serverUrl + "/print-email-accept?id=" + article.getId() + "&key=" + article.getAuthKey();

				strSubject = "[" + serverName + "] Has new article submit with id " + article.getId() + " on " + article.getCreated();
				emails = config.getContactEmail();
				EmailHelper.sendMailFromUrl(serverName + " <" + config.getContactEmail() + ">", strSubject, strUrl, emails);
			}*/
			
			article = new Article();
		}
		
		request.setAttribute("check", check);
		request.setAttribute("article", article);
		request.setAttribute("categories", categories);
		request.setAttribute("url", url);
		try {
			request.getRequestDispatcher("/pages/submit_article.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
